<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.court_delete"
          @click="handleDelete">删 除
        </el-button>
      </template>

      <template #menu="{ size, row }">
        <el-button @click="openPackageDialog(row)" text type="text" :size="size">
          套餐管理
        </el-button>

        <el-button @click="openTimeDialog(row)" text type="text" :size="size">
          场次管理
        </el-button>
      </template>
    </avue-crud>

    <!-- 套餐管理弹框 -->
    <el-dialog title="套餐管理" :visible.sync="packageDialogVisible" width="1000px" append-to-body>
      <div class="package-container">
        <div class="package-header" style="margin-bottom: 10px;">
          <el-button type="primary" size="small" @click="addPackage" icon="el-icon-plus">新增套餐</el-button>
        </div>
        <el-table :data="packageList" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="170"></el-table-column>
          <el-table-column prop="name" label="套餐名称" min-width="120"></el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
          <el-table-column prop="details" label="详情" min-width="200"></el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="editPackage(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deletePackage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 套餐编辑弹框 -->
    <el-dialog :title="packageForm.id ? '编辑套餐' : '新增套餐'" :visible.sync="packageEditDialogVisible" width="600px"
      append-to-body>
      <el-form :model="packageForm" ref="packageForm" :rules="packageRules" label-width="100px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="packageForm.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="packageForm.price" :precision="2" :step="10" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="详情" prop="details">
          <el-input v-model="packageForm.details" type="textarea" :rows="3" placeholder="请输入套餐详情"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="packageForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="packageEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePackage">确定</el-button>
      </div>
    </el-dialog>

    <!-- 场次管理弹框 -->
    <el-dialog title="场次管理" :visible.sync="timeDialogVisible" width="1000px" append-to-body>
      <div class="time-container">
        <div class="time-header" style="margin-bottom: 10px;">
          <el-date-picker :clearable="false" v-model="selectedDate" type="date" placeholder="选择日期"
            value-format="yyyy-MM-dd" @change="handleDateChange"
            style="width: 200px; margin-right: 15px;"></el-date-picker>
          <el-button type="primary" size="small" @click="addTime" icon="el-icon-plus">新增场次</el-button>
          <el-button type="primary" size="small" @click="setTime" icon="el-icon-plus">批量设置场次</el-button>

        </div>
        <el-table :data="timeList" border style="width: 100%">
          <el-table-column prop="id" label="ID" width="170"></el-table-column>
          <el-table-column prop="courtDate" label="日期"></el-table-column>
          <el-table-column prop="startTime" label="开始时间"></el-table-column>
          <el-table-column prop="endTime" label="结束时间"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="170">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="editTime(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteTime(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 场次编辑弹框 -->
    <el-dialog :title="timeForm.id ? '编辑场次' : '新增场次'" :visible.sync="timeEditDialogVisible" width="600px"
      append-to-body>
      <el-form :model="timeForm" ref="timeForm" :rules="timeRules" label-width="100px">
        <el-form-item label="日期" prop="courtDate">
          <el-date-picker v-model="timeForm.courtDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker v-model="timeForm.startTime" format="HH:mm" value-format="HH:mm" placeholder="选择开始时间"
            style="width: 100%;"></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker v-model="timeForm.endTime" format="HH:mm" value-format="HH:mm" placeholder="选择结束时间"
            style="width: 100%;"></el-time-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="timeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="timeEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTime">确定</el-button>
      </div>
    </el-dialog>

    <!-- 批量设置场次弹框 -->
    <el-dialog title="批量设置场次" :visible.sync="batchTimeDialogVisible" width="650px" append-to-body>
      <div class="batch-time-container">
        <el-form :model="batchTimeForm" ref="batchTimeForm" :rules="batchTimeRules" label-width="100px">
          <el-form-item label="起止日期" prop="dateRange">
            <el-date-picker v-model="batchTimeForm.dateRange" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
              style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="开放时间" prop="openTime">
            <el-time-picker v-model="batchTimeForm.startTime" format="HH:mm" value-format="HH:mm" placeholder="开始时间"
              style="width: 45%;"></el-time-picker>
            <span style="margin: 0 10px;">-</span>
            <el-time-picker v-model="batchTimeForm.endTime" format="HH:mm" value-format="HH:mm" placeholder="结束时间"
              style="width: 45%;"></el-time-picker>
          </el-form-item>
          <el-form-item label="快捷操作">
            <div class="batch-time-buttons" style="padding-top: 3px;">
              <el-button type="primary" size="medium" @click="generateTimeSlotsWithInterval(2)">每2小时一场生成</el-button>
              <el-button type="primary" size="medium" @click="generateTimeSlotsWithInterval(1)">每1小时一场生成</el-button>
            </div>
          </el-form-item>
          <el-form-item label="场次时间">
            <div class="time-slots-container">
              <div v-for="(slot, index) in timeSlots" :key="index" class="time-slot-tag">
                {{ slot.startTime }}-{{ slot.endTime }}
                <i class="el-icon-close" @click="removeTimeSlot(index)"></i>
              </div>
              <div style="padding: 0;" v-if="timeSlots.length === 0" class="no-time-slots">
                未设置场次，请通过快捷操作生成场次
              </div>
            </div>
          </el-form-item>
          <el-form-item label="">
            <div class="batch-time-hint">
              提示：配置会删除选中的日期的全部已有场次，请慎重配置
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchTimeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBatchTime">保存场次</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/lanqiu/court";
import { getList as getPackageList, getDetail as getPackageDetail, add as addPackage, update as updatePackage, remove as removePackage } from "@/api/lanqiu/courtPackage";
import { getListByCourt as getTimeList, getDetail as getTimeDetail, add as addTime, update as updateTime, remove as removeTime, saveBatchTime } from "@/api/lanqiu/courtTime";
import option from "@/const/lanqiu/court";
import { mapGetters } from "vuex";

export default {
  data() {
    // 校验结束时间不能早于开始时间
    const validateEndTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束时间'));
      } else if (!this.timeForm.startTime) {
        callback(new Error('请先选择开始时间'));
      } else {
        const startTime = this.timeForm.startTime;
        const endTime = value;
        if (endTime <= startTime) {
          callback(new Error('结束时间不能早于或等于开始时间'));
        } else {
          callback();
        }
      }
    };

    // 校验批量设置中结束时间不能早于开始时间
    const validateBatchEndTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束时间'));
      } else if (!this.batchTimeForm.startTime) {
        callback(new Error('请先选择开始时间'));
      } else {
        const startTime = this.batchTimeForm.startTime;
        const endTime = value;
        if (endTime <= startTime) {
          callback(new Error('结束时间不能早于或等于开始时间'));
        } else {
          callback();
        }
      }
    };

    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      // 套餐管理相关数据
      packageDialogVisible: false,
      packageEditDialogVisible: false,
      currentCourt: null,
      packageList: [],
      packageForm: {
        id: '',
        courtId: '',
        name: '',
        price: 0,
        details: '',
        status: 1
      },
      packageRules: {
        name: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入套餐价格', trigger: 'blur' }
        ],
        details: [
          { required: true, message: '请输入套餐内容', trigger: 'blur' }
        ]
      },
      // 场次管理相关数据
      timeDialogVisible: false,
      timeEditDialogVisible: false,
      selectedDate: new Date().toISOString().slice(0, 10), // 默认当天
      timeList: [],
      timeForm: {
        id: '',
        courtId: '',
        courtDate: new Date().toISOString().slice(0, 10),
        startTime: '',
        endTime: '',
        status: 1
      },
      timeRules: {
        courtDate: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          { validator: validateEndTime, trigger: 'change' }
        ]
      },
      // 批量设置场次相关数据
      batchTimeDialogVisible: false,
      batchTimeForm: {
        dateRange: [],
        startTime: '08:00',
        endTime: '22:00',
      },
      batchTimeRules: {
        dateRange: [
          { required: true, type: 'array', message: '请选择起止日期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          { validator: validateBatchEndTime, trigger: 'change' }
        ]
      },
      timeSlots: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.court_add, false),
        viewBtn: this.vaildData(this.permission.court_view, false),
        delBtn: this.vaildData(this.permission.court_delete, false),
        editBtn: this.vaildData(this.permission.court_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    // 套餐管理相关方法
    openPackageDialog(row) {
      this.currentCourt = row;
      this.packageDialogVisible = true;
      this.loadPackageList(row.id);
    },
    // 球场场次管理
    openTimeDialog(row) {
      this.currentCourt = row;
      this.timeDialogVisible = true;
      this.loadTimeList(row.id, this.selectedDate);
    },
    // 批量设置场次
    setTime() {
      // this.currentCourt = this.currentCourt;
      // 初始化批量设置表单和场次数据
      this.batchTimeForm = {
        dateRange: [],
        startTime: this.currentCourt.startTime || '08:00',
        endTime: this.currentCourt.endTime || '20:00'
      };
      this.timeSlots = [];
      this.batchTimeDialogVisible = true;
    },
    // 根据时间间隔生成场次
    generateTimeSlotsWithInterval(hourInterval) {
      // 验证表单
      this.$refs.batchTimeForm.validate((valid) => {
        if (valid) {
          const { startTime, endTime } = this.batchTimeForm;

          // 转换时间为分钟
          const startMinutes = this.timeToMinutes(startTime);
          const endMinutes = this.timeToMinutes(endTime);

          if (startMinutes >= endMinutes) {
            this.$message.warning('开始时间必须早于结束时间');
            return;
          }


          // 以小时为间隔生成场次时间
          const intervalMinutes = hourInterval * 60;
          this.timeSlots = [];

          for (let time = startMinutes; time < endMinutes - intervalMinutes; time += intervalMinutes) {
            const slotStartTime = this.minutesToTime(time);
            const slotEndTime = this.minutesToTime(time + intervalMinutes);

            this.timeSlots.push({
              startTime: slotStartTime,
              endTime: slotEndTime
            });
          }
        }
      });
    },
    // 移除时间段
    removeTimeSlot(index) {
      this.timeSlots.splice(index, 1);
    },
    // 转换时间格式为分钟数 (HH:mm -> minutes)
    timeToMinutes(time) {
      const [hours, minutes] = time.split(':').map(Number);
      return hours * 60 + minutes;
    },
    // 转换分钟数为时间格式 (minutes -> HH:mm)
    minutesToTime(minutes) {
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`;
    },
    // 保存批量场次
    saveBatchTime() {
      // 验证表单
      this.$refs.batchTimeForm.validate((valid) => {
        if (valid) {
          if (this.timeSlots.length === 0) {
            this.$message.warning('请先生成场次');
            return;
          }

          const { dateRange } = this.batchTimeForm;
          if (!dateRange || dateRange.length !== 2) {
            this.$message.warning('请选择有效的日期范围');
            return;
          }

          // 获取日期范围内的所有日期
          const startDate = new Date(dateRange[0]);
          const endDate = new Date(dateRange[1]);
          const dateList = [];

          for (let date = new Date(startDate); date <= endDate; date.setDate(date.getDate() + 1)) {
            dateList.push(date.toISOString().slice(0, 10));
          }

          // 生成批量场次数据
          const batchTimeData = [];

          dateList.forEach(date => {
            this.timeSlots.forEach(slot => {
              batchTimeData.push({
                courtId: this.currentCourt.id,
                courtDate: date,
                startTime: `${date} ${slot.startTime}`,
                endTime: `${date} ${slot.endTime}`,
                status: 1
              });
            });
          });

          // 调用批量保存接口
          saveBatchTime(batchTimeData).then(() => {
            this.$message.success('批量设置场次成功');
            this.batchTimeDialogVisible = false;

            // 如果当前查看的日期在范围内，刷新场次列表
            if (this.selectedDate >= dateRange[0] && this.selectedDate <= dateRange[1]) {
              this.loadTimeList(this.currentCourt.id, this.selectedDate);
            }
          }).catch(err => {
            console.error(err);
            this.$message.error('批量设置场次失败');
          });
        }
      });
    },
    // 日期选择变更
    handleDateChange(date) {
      this.loadTimeList(this.currentCourt.id, date);
    },
    // 加载场次列表
    loadTimeList(courtId, date) {
      getTimeList(1, 100, { courtId, date }).then(res => {
        this.timeList = res.data.data;
      });
    },
    // 添加场次
    addTime() {
      this.timeForm = {
        courtId: this.currentCourt.id,
        courtDate: this.selectedDate,
        startTime: '',
        endTime: '',
        status: 1
      };
      this.timeEditDialogVisible = true;
    },
    // 编辑场次
    editTime(row) {
      getTimeDetail(row.id).then(res => {
        const timeData = res.data.data;
        // 处理日期和时间格式
        if (timeData.startTime && timeData.startTime.includes(' ')) {
          const [date, startTime] = timeData.startTime.split(' ');
          timeData.courtDate = date;
          timeData.startTime = startTime;
        }
        if (timeData.endTime && timeData.endTime.includes(' ')) {
          timeData.endTime = timeData.endTime.split(' ')[1];
        }
        this.timeForm = timeData;
        this.timeEditDialogVisible = true;
      });
    },
    // 保存场次
    saveTime() {
      this.$refs.timeForm.validate(valid => {
        if (valid) {
          const isAdd = !this.timeForm.id;
          const apiFunc = isAdd ? addTime : updateTime;

          // 深拷贝表单数据
          const formData = JSON.parse(JSON.stringify(this.timeForm));
          // 拼接日期和时间
          formData.startTime = `${formData.courtDate} ${formData.startTime}`;
          formData.endTime = `${formData.courtDate} ${formData.endTime}`;

          apiFunc(formData).then(() => {
            this.$message.success('保存成功');
            this.timeEditDialogVisible = false;
            this.loadTimeList(this.currentCourt.id, this.selectedDate);
          });
        }
      });
    },
    // 删除场次
    deleteTime(row) {
      this.$confirm('确认删除该场次?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeTime(row.id).then(() => {
          this.$message.success('删除成功');
          this.loadTimeList(this.currentCourt.id, this.selectedDate);
        });
      });
    },
    // 加载套餐列表
    loadPackageList(courtId) {
      getPackageList(1, 100, { courtId }).then(res => {
        this.packageList = res.data.data.records;
      });
    },
    // 添加套餐
    addPackage() {
      this.packageForm = {
        courtId: this.currentCourt.id,
        name: '',
        price: 0,
        details: '',
        status: 1
      };
      this.packageEditDialogVisible = true;
    },
    // 编辑套餐
    editPackage(row) {
      getPackageDetail(row.id).then(res => {
        this.packageForm = res.data.data;
        this.packageEditDialogVisible = true;
      });
    },
    // 保存套餐
    savePackage() {
      this.$refs.packageForm.validate(valid => {
        if (valid) {
          const isAdd = !this.packageForm.id;
          const apiFunc = isAdd ? addPackage : updatePackage;

          apiFunc(this.packageForm).then(() => {
            this.$message.success('保存成功');
            this.packageEditDialogVisible = false;
            this.loadPackageList(this.currentCourt.id);
          });
        }
      });
    },
    // 删除套餐
    deletePackage(row) {
      this.$confirm('确认删除该套餐?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePackage(row.id).then(() => {
          this.$message.success('删除成功');
          this.loadPackageList(this.currentCourt.id);
        });
      });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style scoped>
.package-container {
  padding: 10px;
}

.package-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.time-container {
  padding: 10px;
}

.time-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.batch-time-container {
  padding: 10px;
}

.batch-time-title {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 10px;
  color: #303133;
}

.batch-time-operations {
  margin-top: 20px;
  margin-bottom: 20px;
}

.batch-time-buttons {
  display: flex;
  gap: 10px;
}

.batch-time-preview {
  margin-top: 20px;
  margin-bottom: 20px;
}

.time-slots-container {
  gap: 10px;
  display: flex;
  flex-wrap: wrap;
}

.time-slot-tag {
  padding: 6px 12px;
  background-color: #f2f6fc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  position: relative;
}

.time-slot-tag .el-icon-close {
  margin-left: 5px;
  cursor: pointer;
  color: #909399;
}

.time-slot-tag .el-icon-close:hover {
  color: #409EFF;
}

.no-time-slots {
  color: #909399;
  font-size: 14px;
}

.batch-time-hint {
  color: #f1a22c;
  font-size: 14px;
}
</style>
